package com.bibrApp.difu.fragment.jiedai_mvp;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.R;
import com.bibrApp.difu.Response.C2CJiedaiResBody;
import com.bibrApp.difu.Response.TradePawnInfo;
import com.bibrApp.difu.actvity.jiechu_mvp.JiechuActivity;
import com.bibrApp.difu.actvity.jiedai_manager_mvp.JiedaiManagerActivity;
import com.bibrApp.difu.actvity.login_mvp.LoginActivity;
import com.bibrApp.difu.actvity.order_message_mvp.OrderMessageActivity;
import com.bibrApp.difu.actvity.others.HelpActivity;
import com.bibrApp.difu.actvity.publist_jieru_mvp.PublistJieruActivity;
import com.bibrApp.difu.base.BaseFragment;
import com.bibrApp.difu.utils.CheckUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.google.android.material.appbar.AppBarLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class JiedaiFragment extends BaseFragment<JiedaiPresenter> implements IJiedaiView {


    @BindView(R.id.ll_top)
    View llTop;
    @BindView(R.id.appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.tv_btc)
    TextView tvBtc;
    @BindView(R.id.tv_eth)
    TextView tvEth;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @BindView(R.id.tv_jieru)
    TextView tvJieru;
    @BindView(R.id.tv_jiechu)
    TextView tvJiechu;
    @BindView(R.id.tv_jieru_below)
    View jieruBelow;
    @BindView(R.id.tv_jiechu_below)
    View jiechuBelow;
    @BindView(R.id.tv_info1)
    TextView tvInfo1;
    @BindView(R.id.tv_info2)
    TextView tvInfo2;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_shouyi)
    TextView tvShouyi;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.iv_visible)
    ImageView ivVisibe;

    boolean isVisible = true;
    private JiedaiAdapter adapter;
    private PopupWindow popupWindow;

    String direction = "1";
    String type = "BTC";
    String date = "";
    private DfApp app;
    private static final int pageSize = 10;
    private int pageNum = 1;


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_jiedai;
    }

    @Override
    protected void initPresenter() {
        presenter = new JiedaiPresenter(getContext(), this);
        presenter.init();
    }

    @Override
    public void error(String msg) {

    }

    List<C2CJiedaiResBody.JiedaiBean> mDatas = new ArrayList<>();

    @Override
    public void onDatas(C2CJiedaiResBody datas) {
        if (datas.getList() == null || datas.getList().size() < 1) {
            mDatas.clear();
            adapter.notifyDataSetChanged();
            return;
        }
        mDatas = datas.getList();
        adapter.setNewData(mDatas);
    }

    private TradePawnInfo tradePawnInfo;
    private List<TradePawnInfo> tradePawnInfos = new ArrayList<>();

    @Override
    public void successOfTradeBInfo(List<TradePawnInfo> tradePawnInfos) {
        if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
            this.tradePawnInfos = tradePawnInfos;
            for (int i = 0; i < tradePawnInfos.size(); i++) {
                if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase("BTC")) {
                    tradePawnInfo = tradePawnInfos.get(i);
                }
            }
            if (tradePawnInfo == null) {
                return;
            }
            presenter.getData(pageSize, pageNum, 0, 2, tradePawnInfo.getId(), "", sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
        }
    }

    private boolean mHasPaySetting = false;
    private boolean mHasMoney = false;

    @Override
    public void successOfGetPaySetting(boolean hasPaySetting) {
        mHasPaySetting = hasPaySetting;
    }

    @Override
    public void successOfGetAllAssets(boolean hasMoney) {
        mHasMoney = hasMoney;
    }

    @Override
    public void initView() {
        app = (DfApp) getActivity().getApplication();

        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            int scrollRangle = appBarLayout.getTotalScrollRange();
            //初始verticalOffset为0，不能参与计算。
            if (verticalOffset == 0) {

            } else {
                //保留一位小数
                if (verticalOffset < -700) {
                    llTop.setBackgroundResource(R.color.white);
                } else {
                    llTop.setBackgroundResource(R.color.white_c_alpha);
                }

            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new JiedaiAdapter();
        recyclerView.setAdapter(adapter);
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.tv_jiechu) {
                Bundle bundle = new Bundle();
                if (mDatas != null) {
                    bundle.putSerializable("bean", mDatas.get(position));
                }
                if (CheckUtils.checkUser(getContext(), app, mHasPaySetting, mHasMoney)) {
                    IntentUtil.toActivity(JiechuActivity.class, this, bundle);
                }
            }
        });
        presenter.getTradeBInfo();
        presenter.getAllPaySetting();
        presenter.queryAllAssets();
    }

    @OnClick(R.id.bt_help)
    public void helpClick() {
        startActivity(new Intent(getContext(), HelpActivity.class));
    }

    private int cyclePos;
    private int sortPos;
    private String cycle;

    @OnClick(R.id.tv_shaixuan)
    public void shaixuanClick() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }

        View layout = View.inflate(getContext(), R.layout.pop_c2c_shaixuan, null);

        RecyclerView listSort = layout.findViewById(R.id.recycler_view);
        RecyclerView listDay = layout.findViewById(R.id.recycler_view2);
        listSort.setLayoutManager(new GridLayoutManager(getContext(), 3));
        listDay.setLayoutManager(new GridLayoutManager(getContext(), 3));


        TabAdapter sortAdapter = new TabAdapter();
        listSort.setAdapter(sortAdapter);
        sortAdapter.setOnItemClickListener((adapter1, view, position) -> {
            sortPos = position;
            sortAdapter.setSelected(position);
        });
        List<String> sortData = new ArrayList<>();
        sortData.add("年化增序");
        sortData.add("金额降序");
        sortData.add("质押率升序");

        sortAdapter.setSelected(sortPos);
        sortAdapter.setNewData(sortData);

        TabAdapter dayAdapter = new TabAdapter();
        listDay.setAdapter(dayAdapter);
        dayAdapter.setOnItemClickListener((adapter1, view, position) -> {
            cyclePos = position;
            dayAdapter.setSelected(position);
        });
        List<String> dayData = new ArrayList<>();
        dayData.add("全部");
        dayData.add("7天");
        dayData.add("15天");
        dayData.add("30天");
        dayData.add("60天");
        dayData.add("90天");
        dayData.add("180天");
        dayAdapter.setNewData(dayData);
        dayAdapter.setSelected(cyclePos);


        popupWindow = new PopupWindow(layout, -1, -2, true);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor((view, motionEvent) -> {
            return false;
        });


        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#88000000")));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (cyclePos != 0) {
                    String cycleStr = dayData.get(cyclePos);
                    cycle = cycleStr.substring(0, dayData.get(cyclePos).length()-1);
                }

                presenter.getData(pageSize, pageNum, 0, 2, tradePawnInfo.getId(), cycle, sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
            }
        });


        popupWindow.showAsDropDown(llTop, 0, 0);
    }


    @OnClick(R.id.tv_jieru)
    public void jieruClick() {
        tvJieru.setTextColor(Color.WHITE);
        tvJiechu.setTextColor(Color.parseColor("#88FFFFFF"));
        jieruBelow.setVisibility(View.VISIBLE);
        jiechuBelow.setVisibility(View.INVISIBLE);

        tvInfo1.setText("当前借款金额(USDT)");
        tvInfo2.setText("累计借款金额(USDT)");
        tvShouyi.setText("累计利息(USDT)≈50.39");
        tvDay.setText("最近还款日5天后");

        //presenter.getData(pageSize, pageNum, 0, 1, tradePawnInfo.getId(), "", sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
    }

    @OnClick(R.id.tv_jiechu)
    public void jiechuClick() {
        tvJiechu.setTextColor(Color.WHITE);
        tvJieru.setTextColor(Color.parseColor("#88FFFFFF"));
        jiechuBelow.setVisibility(View.VISIBLE);
        jieruBelow.setVisibility(View.INVISIBLE);

        tvInfo1.setText("当前借出金额(USDT)");
        tvInfo2.setText("累计借款金额(USDT)");
        tvShouyi.setText("累计收益(USDT)≈50.39");
        tvDay.setText("最近收款日8天后");

        //presenter.getData(pageSize, pageNum, 0, 0, tradePawnInfo.getId(), "", sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
    }

    @OnClick(R.id.iv_visible)
    public void visibleClick() {
        isVisible = !isVisible;
        if (isVisible) {
            tvNum.setText("8000");
            tvDay.setText("123,456");
        } else {
            tvNum.setText("****");
            tvDay.setText("****");
        }
    }

    @OnClick(R.id.tv_btc)
    public void btcClick() {
        tvBtc.setBackgroundResource(R.drawable.bg_jiedai_tab_left);
        tvEth.setBackgroundResource(R.drawable.bg_jiedai_tab_right);
        tvBtc.setTextColor(Color.WHITE);
        tvEth.setTextColor(getResources().getColor(R.color.blue_e4));

        type = "BTC";
        if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
            for (int i = 0; i < tradePawnInfos.size(); i++) {
                if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase(type)) {
                    tradePawnInfo = tradePawnInfos.get(i);
                }
            }
        }
        if (tradePawnInfo == null) {
            return;
        }
        presenter.getData(pageSize, pageNum, 0, 2, tradePawnInfo.getId(), "", sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);

    }

    @OnClick(R.id.tv_eth)
    public void ethClick() {
        tvBtc.setBackgroundResource(R.drawable.bg_jiedai_tab_left2);
        tvEth.setBackgroundResource(R.drawable.bg_jiedai_tab_right2);
        tvBtc.setTextColor(getResources().getColor(R.color.blue_e4));
        tvEth.setTextColor(getResources().getColor(R.color.white));

        type = "ETH";
        if (tradePawnInfos != null && tradePawnInfos.size() > 0) {
            for (int i = 0; i < tradePawnInfos.size(); i++) {
                if (tradePawnInfos.get(i).getEunit().equalsIgnoreCase(type)) {
                    tradePawnInfo = tradePawnInfos.get(i);
                }
            }
        }
        if (tradePawnInfo == null) {
            return;
        }
        presenter.getData(pageSize, pageNum, 0, 2, tradePawnInfo.getId(), "", sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
    }

    private static final int REQUEST_ID = 0x11;

    @OnClick(R.id.ll_fabu)
    public void publishClick() {
        if (CheckUtils.checkUser(getContext(), app, mHasPaySetting, mHasMoney)) {
            IntentUtil.toActivityForResult(PublistJieruActivity.class, this, REQUEST_ID);
        }
    }

    @OnClick(R.id.ll_order)
    public void orderClick() {
        startActivity(new Intent(getContext(), OrderMessageActivity.class));
    }

    @OnClick(R.id.ll_manager)
    public void managerClick() {
        startActivity(new Intent(getContext(), JiedaiManagerActivity.class));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ID) {
            presenter.getData(pageSize, pageNum, 0, 2, tradePawnInfo.getId(), cycle, sortPos == 1 ? 1 : 0, sortPos == 0 ? 0 : 1, 0, sortPos == 2 ? 1 : 0);
        }
    }
}
